import { fetchViewResource } from "./services/auth/auth";
import { AppViewResource, DynamicComponent, appViewResources, deepClone, defaultViewResponse } from "./global";
import { message } from "antd";
import { uniqArray } from "./utils/app_utils";

let extraRoutes: any;

const toMenuTree = (arr: any[], roots: any[]) => {
  if (roots.length === 0) {
    return
  }
  let children: any[] = []
  roots?.forEach(root => {
    const childResources: any[] = arr.filter(item => item.parent === root.name)
    if (childResources && childResources.length > 0) {
      children = [...children, ...childResources]
    }
    root.children = childResources?.map(item => {
      return {
        path: item.path,
        name: item.name,
        element: DynamicComponent(item.component)
      }
    })
  })
  toMenuTree(arr, children)
}

const viewResourceToRouteTree = (arr: any[]): any[] =>  {
  const res: any[] = arr.filter(item => item.parent === null)
  toMenuTree(arr, res)
  return res.map(item => {
    const t: any = {
      path: item.path,
      name: item.name,
      children: item.children
    }
    if (item?.component) {
      t.element = DynamicComponent(item.component)
    }
    return t
  })
}

/**
 * 根据后台数据更新路由
 * 路由修改格式：https://reactrouter.com/en/main/hooks/use-routes
 */
export function patchClientRoutes({ routes }: {routes: any[]}) {
  // 服务端配置的视图资源
  if (!extraRoutes) {
    return
  }
  const {total, data} = extraRoutes
  if (!data) {
    return
  }
  const canViewResource: AppViewResource[] = []
  data.forEach((item: any) => {
    const idx = appViewResources.findIndex(view => view.name === item.name)
    if (idx !== -1) {
      canViewResource.push(deepClone(appViewResources[idx]))
    }
  })
  const resultRoutes: any[] = viewResourceToRouteTree(canViewResource)
  // 0层固定为布局
  if (routes[0].children) {
    routes[0].children = [...resultRoutes, ...routes[0].children]
  } else {
    routes[0].children = [...resultRoutes]
  }
  // 合并存在前后端配置了相同的页面，去重
  if (routes[0].children) {
    routes[0].children = uniqArray(routes[0].children, (item: any) => (item.path ? item.path : "") + item.name)
  }
  // 默认不存在的页面。（绝对路径+根路径布局组件的做法，实际上不会走到这个地方，上面的路径匹配已经处理完所有了，这里保留放置根组件不使用布局组件）
  routes.push({ path: '*', element: DynamicComponent('@/pages/404') })
  console.log("routes: ", routes)
}

const initUiComponentConfiguration = () => {
  message.config({
    duration: 1,
    maxCount: 1
  })
}

export function render(oldRender: any) {
  const hide = message.loading("页面资源加载中", 10);
  fetchViewResource()
    .then((res) => {
      extraRoutes = res;
      initUiComponentConfiguration()
      oldRender();
      hide()
    });
}
